using System;
using System.Reflection;

using SBPweb.Modules.Modularity;
using SBPweb.Contracts;
using SBPweb.Contracts.Implementation;
using SBPweb.Contracts.WebBrowser;

// This alias is needed for the module loader to recognize the module's entry point
[assembly: AssemblyDefaultAlias("SBPweb.Modules.WebBrowser.WebBrowserModule")]

namespace SBPweb.Modules.WebBrowser
{
	public class WebBrowserModule : ModuleBase
	{
		WebBrowserControl mWebBrowserControl;
		ModuleLoader mParent;

		#region Constructor logic

		public WebBrowserModule(IModuleHost host)
            : base(host)
        {
			mParent = host.ModuleLoader;
			Name = "SBPweb.Modules.WebBrowser";
            pIcon = Properties.Resources.IE;

            mWebBrowserControl = new WebBrowserControl(this);
            mWebBrowserControl.Dock = System.Windows.Forms.DockStyle.Fill;

            (mWebBrowserControl as System.Windows.Forms.Control).Text = "Web browser";

			Services.Put<IWebBrowserService>(mWebBrowserControl);
        }

		public override void Initialize()
		{
			if (HostType != ModuleHostType.WindowsForms)
			{
				Host.LogManager.WriteError(this, "The host is not WinForm", "WebBrowser");
				return;
			}

			Host.Smartparts.Add(mWebBrowserControl);
			LoadPersistency();
		}

		#endregion

		#region Persistency

		public override void SavePersistency()
		{
			IStatePersistenceService persistenceService = Services.Get<IStatePersistenceService>();
			if (persistenceService != null && mWebBrowserControl != null)
			{
				PersistencyDictionary state = persistenceService.Load(this);
				mWebBrowserControl.SavePersistence(state);
				persistenceService.Save(this, state);
				Host.LogManager.WriteVerbose(this, "Persistency saved for webbrowser module.", "WebBrowser");
			}
		}

		public override void LoadPersistency()
		{
			IStatePersistenceService persistenceService = Services.Get<IStatePersistenceService>();
			if (persistenceService != null)
			{
				PersistencyDictionary state = persistenceService.Load(this);
				mWebBrowserControl.LoadPersistence(state);
				Host.LogManager.WriteVerbose(this, "Persistency loaded for webbrowser module.", "WebBrowser");
			}
		}

		#endregion

		public override void Terminate()
		{
			SavePersistency();
			Services.Remove(typeof(IWebBrowserService));
			Host.Smartparts.Remove(mWebBrowserControl);
            try
            {
                mWebBrowserControl.Dispose();
                mWebBrowserControl = null;
            }
            catch
            {
                //do nothing!!
            }
		}
	}
}
